/**
 * 
 */
package nl.samenloop.bigscreen;

import java.util.ArrayList;
import java.util.List;

import nl.samenloop.bigscreen.sequence.ClockSequence;
import nl.samenloop.bigscreen.sequence.DrawingTarget;
import nl.samenloop.bigscreen.sequence.ProgramSequence;
import nl.samenloop.bigscreen.sequence.Sequence;
import nl.samenloop.bigscreen.sequence.SequenceStartListener;
import nl.samenloop.bigscreen.sequence.TwitterSequence;
import nl.samenloop.bigscreen.sequence.WeatherSequence;

/**
 * @author Bram Wiekens
 * 
 */
public class Sequencer implements SequenceStartListener {

	private List<Sequence> sequences = new ArrayList<Sequence>();

	private DrawingTarget target;
	private ClockSequence cs;
	private Thread sequenceThread;

	public Sequencer(DrawingTarget target) {
		initSequences(target);

		this.target = target;

		firstSequence();

		
	}

	private void firstSequence() {
		cs = new ClockSequence(target, this);
		cs.start();
	}

	@Override
	public synchronized void start() {
		cs.stop();

		try {
			Thread.sleep(2500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		target.showClock(cs.getStart());

		startSequences();
	}

	private void startSequences() {

		sequenceThread = new Thread(new Runnable() {

			@Override
			public void run() {
				int i = 0;
				Sequence seq0 = sequences.get(i);
				seq0.prepare();

				while (true) {
					Sequence sequence = sequences.get(i);
					Sequence next = sequences.get((i + 1) % sequences.size());

					next.prepare();
					sequence.start();

					int wait = sequence.getRequiredTime();

					try {
						Thread.sleep(wait + 1500);
						sequence.stop();
						Thread.sleep(1500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					i = (i + 1) % sequences.size();
				}

			}
		});
		sequenceThread.start();

	}

	private void initSequences(DrawingTarget target) {
		TwitterSequence twitter = new TwitterSequence(target);

		ProgramSequence program0 = new ProgramSequence(target, ProgramSequence.NOW_STAGE);
		ProgramSequence program1 = new ProgramSequence(target, ProgramSequence.NEXT_STAGE);
		ProgramSequence program2 = new ProgramSequence(target, ProgramSequence.NOW_FIELD);
		ProgramSequence program3 = new ProgramSequence(target, ProgramSequence.NEXT_FIELD);

		WeatherSequence weather = new WeatherSequence(target);

		//sequences.add(twitter);
		sequences.add(program0);
		sequences.add(program1);
		sequences.add(weather);
		sequences.add(program2);
		sequences.add(program3);

	}

}
